package com.mapforge.gui;

import java.awt.event.ActionEvent;
import java.util.Iterator;

import com.mapforge.ActionCommands;
import com.mapforge.gui.interfaces.CutCopyPasteListenerInterface;
import com.mapforge.gui.interfaces.TileMapEditorGUIInterface;
import com.mapforge.gui.tools.SelectedTiles;
import com.mapforge.listener.TileLayerDeletionEvent;
import com.mapforge.listener.TileLayerSelectionEvent;
import com.mapforge.listener.TileMapCreationEvent;
import com.mapforge.map.TileLayer;
import com.mapforge.map.tools.TileClipboard;

public abstract class AbstractCutCopyPasteListener implements
		CutCopyPasteListenerInterface {

	private TileLayer layer;
	private TileMapEditorGUIInterface mapEditorGUI;

	public AbstractCutCopyPasteListener(TileMapEditorGUIInterface mapEditorGUI) {
		this.mapEditorGUI = mapEditorGUI;
	}

	public TileMapEditorGUIInterface getTileMapEditorGUI() {
		return this.mapEditorGUI;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		String s = e.getActionCommand();
		SelectedTiles selection = SelectedTiles.getHandle();
		TileClipboard clipboard = TileClipboard.getHandle();
		if (s.equals(ActionCommands.CUT_TILES_CMD) && !selection.isEmpty()) {
			this.cutTiles();
		} else if (s.equals(ActionCommands.COPY_TILES_CMD)
				&& !selection.isEmpty()) {
			this.copyTiles();
		} else if (s.equals(ActionCommands.PASTE_TILES_CMD)
				&& !clipboard.isEmpty()) {
			this.pasteTiles();
		} else if (s.equals(ActionCommands.PASTE_TILES_AT_LOCATION_CMD)) {
			this.pasteTilesAtLocation();
		}

	}

	@Override
	public void tileLayerSelectionPerformed(TileLayerSelectionEvent event) {
		if (event.getNumberLayersSelected() == 1) {
			Iterator<TileLayer> it = event.iterator();
			this.layer = it.next();
		} else {
			this.layer = null;
		}
	}

	@Override
	public void tileMapCreationPerformed(TileMapCreationEvent mapCreationEvent) {
		this.layer = null;
	}

	@Override
	public void tileLayerDeletionPerformed(TileLayerDeletionEvent event) {
		Iterator<TileLayer> it = event.getDeletedLayerIterator();
		while (it.hasNext()) {
			if (it.next() == this.getLayer()) {
				this.layer = null;
				break;
			}
		}
	}

	public TileLayer getLayer() {
		return this.layer;
	}
}
